<?php

namespace App\Http\Controllers\Admin;
use Illuminate\Http\Response;
use App\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AdminController extends Controller
{
    /**
     * @var UserRepository
     */
    private $admin;


    /**
     * ApageController constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->admin = new Admin();
    }
    public function  index(){
        $users = $this->admin->orderBy('id', 'desc')->paginate(15, ['*'], 'pageNum');
        return view('admin.Admin.index', compact('users'));
    }
    /**
     * 添加管理员
     *
     * @return Response
     */
    public function create(Request $request)
    {
        if ($request->getMethod() == "POST") {

            $validator = Validator::make($request->all(),
                [
                    'name' => 'required|max:255',
                    'password' => 'required',
                    'email'=>'required',
                ],
                [
                    'name.required' => '管理员名称不能为空',
                    'name.max' => '管理员名称不能大于100个字符',
                    'password.required' => '密码不能为空',
                    'email.required'=>'邮箱不能为空且不能重复',
                ]
            );

            if ($validator->fails()) {
                return view('admin.Admin.create')->withErrors($validator);
            }
            $insert = $this->admin;

            $insert->name= $request->input('name');
            $insert->password= bcrypt($request->input('password'));
            $insert->created_at = time();
            $insert->email = $request->input('email');
            if ($insert->save()) {
                return redirect()->route('admin.Admin.index')->with('success','创建成功!');
            } else {
                return view('admin.Admin.create')->withErrors($insert->save());
            }

        }
        return view('admin.Admin.create');


    }
    /**
     * 管理员密码修改
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit(Request $request,$id)
    {
        $adminObj=$this->admin->find($id);
        dd(encrypt($adminObj->password));
        if (!$adminObj) {
            $errors='内容不存在！';
            return redirect()->route('admin.admin')->withErrors(compact('errors'));
        }
        if($request->getMethod()=="POST"){

            $adminObj->name = $request->input('name');
            $adminObj->password =bcrypt($request->input('password'));
            $adminObj->update();

            return redirect()->route('admin.Admin.index')->with('success','保存成功!');

        }
        return view('admin.Admin.edit', ['admin'=>$adminObj]);
    }

}